type MenuItem = {
  id?: number
  label?: string
  value?: number
  menuId: number
  menuName: string
  parentId: number
  children?: MenuItem[]
}

export const findMenu = function (list: MenuItem[], target: number): MenuItem | void {
  for (let i = 0; i < list.length; i++) {
    const { menuId, children = [] } = list[i]
    if (menuId === target) {
      return list[i]
    } else {
      const result = findMenu(children, target)
      if (result) {
        return result
      }
    }
  }
}

export const buildMenuTree = function (source: MenuItem[]) {
  for (let i = source.length - 1; i >= 0; i--) {
    const child = source[i]

    const { menuId, children = [] } = child
    child.id = menuId
    child.children = children.length ? children : undefined

    for (let j = 0; j < source.length; j++) {
      const parent = source[j]
      const target = findMenu([parent], child.parentId)
      if (target) {
        target.children = [...(target.children || []), child]
        source.splice(i, 1)
      }
    }
  }
  return source
}

export const buildMenuList = function (source: MenuItem[]) {
  for (let i = source.length - 1; i >= 0; i--) {
    const child = source[i]

    const { menuId, menuName, children = [] } = child
    child.id = menuId
    child.label = menuName
    child.value = menuId
    child.children = children.length ? children : undefined

    for (let j = 0; j < source.length; j++) {
      const parent = source[j]
      const target = findMenu([parent], child.parentId)
      if (target) {
        target.children = [...(target.children || []), child]
        source.splice(i, 1)
      }
    }
  }

  return [
    {
      id: 0,
      label: '主类目',
      value: 0,
      children: source
    }
  ]
}